package com.bookmarket.controller;

import com.bookmarket.entity.Book;
import com.bookmarket.entity.Stype;
import com.bookmarket.service.AddBookService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/LAQBook")
public class LAQBookController {

    @Resource
    private AddBookService addbookService;

    @RequestMapping("/addBook")

    public ModelAndView addBook( @RequestParam MultipartFile[] photos,HttpSession session,Book book,String sName ) throws IllegalStateException, IOException{

        //创建文件保存路径
        String path = session.getServletContext().getRealPath("/uploads");
        ModelAndView mv=new ModelAndView();
        Stype stype=new Stype();
        stype.setId(Integer.parseInt(sName));
        //for (int i = 0; i < photos.length; i++) {
            //if(!photos[i].isEmpty()){
                //获取第一个和第二个文件的名称
        String fileName = photos[0].getOriginalFilename();
        String fileName2 = photos[1].getOriginalFilename();
                /*if(fileName.endsWith(".jpg")||fileName.endsWith(".png")||fileName.endsWith(".txt")){*/
        /*System.out.println(fileName);
        System.out.println(fileName2);*/
        //将名称存入数book对象中
        book.setPicture(fileName);
        book.setFile(fileName2);

        File file1 = new File(path, fileName);
        File file2= new File(path, fileName2);

        //完成文件上传
        photos[0].transferTo(file1);
        photos[1].transferTo(file2);
        //将数据存入数据库
        book.setPicture(fileName);
        book.setFile(fileName2);
        book.setStype(stype);
        addbookService.addBook(book);
                /*}else{

                    //失败返回
                    mv.setViewName("redirect:/backstage/LAQBook.ftl");
                    return mv;
                }*/

           // }


        mv.setViewName("redirect:/backstage/LAQBook.ftl");
        return mv;
    }

    @RequestMapping("/getStypes")
    public ModelAndView getStypes(){
        ModelAndView mv=new ModelAndView();
        mv.setView(new MappingJackson2JsonView());


        List<Stype> list=addbookService.selectAll();

        mv.addObject("stype",list);

        return mv;
    }


    public AddBookService getAddBookService() {
        return addbookService;
    }

    public void setAddBookService(AddBookService addbookService) {
        this.addbookService = addbookService;
    }
}
